<template>
<div class="content">
    <div>
      <van-grid :column-num="3" :gutter="10">
        <van-grid-item v-for="item in findService" :key="item.serviceId" class="grid-item">
            <van-image 
                class="service-image"
                height="100" 
                fit="contain"
                :src="item.src"
                @click="toOrder(item.serviceId)"
            />
          <div class="grid-text">{{ item.serviceName }}</div>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
<van-button 
    v-if="isSearching" 
    type="primary"
    class="return-button"
    @click="handleRefresh"
  >
    返回导航
  </van-button>
</template>

<script setup name='Service'>
import { ref, onMounted } from 'vue'
import {getFindServices,getServiceByName} from '../api'
import { emitter } from '../utils/eventBus'
import { useRouter } from 'vue-router'
const findService = ref([])
const router=useRouter()
const active = ref(0)
// 声明 props
const props = defineProps({
  isSearching: {
    type: Boolean,
    default: false
  }
})
// const toOrder=(id)=>{
//   emitter.emit('service-id', { 
//     serviceId: id // 直接传值，避免 Proxy
//    });
//    router.push({ name: "bedInstallation" })
// }
const toOrder = (id) => {
   router.push({ name: "bedInstallation", query: { serviceId: id } });   
}; 
const getList = async (sidebarName) => {
  // console.log('sidebarName', sidebarName.sidebarName)
  try {
    let ret = await getFindServices(sidebarName.sidebarName)
    findService.value = ret
    // console.log('findService', findService.value)
  } catch (e) {
    console.log(e)
  }
}

onMounted(()=>{
    emitter.on('sidebar-type-name', (message) => {
        getList({ sidebarName: message.sidebarName })
  })
  getList({ sidebarName: "家具安装" })
})


// 在Service组件的script部分添加：
const isSearching = ref(false) // 新增搜索状态标识

const searchService = async (serviceName) => {
  try {
    isSearching.value = true // 进入搜索状态
    let ret = await getServiceByName({
      serviceName: serviceName 
    });
    findService.value = ret;
  } catch (e) {
    console.log(e);
  }
}

// 监听搜索事件
emitter.on('search-keyword', (message) => {
  searchService(message.serviceName);
});
const handleRefresh = () => {
  window.location.reload();
};
</script>

<style lang='less' scoped>
.return-button {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  width: 80%;
  max-width: 300px;
}
.grid-text {
  padding: 5px;
  text-align: center;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.service-image {
  width: calc(85vw / 3 - 20px); // 100vw是视图宽度，除以3，减去间距
  max-width: calc(85vw / 3 - 20px);
}
</style>